import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { ActivatedRoute } from '@angular/router';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import { MachineFaultAnalyse } from '../../model/report/machine-fault-analyse';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';
declare const $: any;
import * as Enumerable from 'linq';
import { CommService } from '../../comm/comm.service';
import { DatePipe } from '@angular/common';
@Component({
    selector: 'app-report-mfa',
    templateUrl: './mfa.component.html',
    styleUrls: ['./mfa.component.css'],
    providers: [DatePipe],
})

export class MFAComponent implements OnInit, AfterViewInit {
    [x: string]: any;
    title = '设备故障分析';

    initControl = 1;
    showloading = true;
    public mfaList: MachineFaultAnalyse[];
    public mfaChartsList: MachineFaultAnalyse[];
    public mfaGroupList: MachineFaultAnalyse[];
    public countTopItems: MachineFaultAnalyse[];
    public timeTopItems: MachineFaultAnalyse[];
    public timeChartOption: any;
    public timeChartOptionBar: any;
    public countChartOption: any;
    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];
    public filterValue = 1;
    public subAareSelected: any;
    public shiftSelected: any;

    public equipmentSelected: TVResource[] = [];
  
    constructor(private commServices: CommService,
        public route: ActivatedRoute,private datePipe:DatePipe) {
          
    }

    ngOnInit() {
        console.log('ngOnInit');
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD');
        this.filterValue = 1;
        this.subAreaItems = this.commServices.getSubAreas();
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.route.queryParams.subscribe(params => {
            try {
                if (params['subAreas'] !== undefined && params['time'] !== undefined) {
                    // 根据时间段班次设置时间
                    this.setQueryTime('DateTimeRange', params['time']);
                    this.subAareSelected = this.subAreaItems.find(u => u.subArea === params['subAreas']);
                    this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAareSelected.subArea);
                    this.equipmentSelected = [this.equipemntItems.find(u => u.resource === params['resources'])];
                    this.filterValue = Number.parseInt(params['filterValue']);
                    const shift = JSON.parse(params['shift']);
                    const a = this.shiftItems.find(e => e.shiftId === shift.shiftId);
                    this.shiftSelected = a;
                    this.getReportData();
                }
            } catch (error) {
                console.log(error.resultMessage);
            }
        });
        if (this.subAareSelected === undefined) {
            this.subAareSelected = this.subAreaItems[0];
            this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
            this.equipmentSelected = this.equipemntItems;
        }
    }

    onSubAreaSelectedChange(): void {
        if (this.initControl > 1) {
            this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAareSelected.subArea);
            this.equipmentSelected = this.equipemntItems;
        } else {
            this.initControl++;
        }
    }
    /**
     * 获取TimeRange的值
     * @param id id
     */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }
    setQueryTime(id: any, value: String) {
        $('#' + id).val(value);
    }
    ngAfterViewInit() {
    }

    /**获取表格数据*/
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.filterValue = this.filterValue;
        this.commServices
            .getList(queryModel, ReportUrls.MFAUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.mfaList = <any>Enumerable.from((<MachineFaultAnalyse[]>model.data)).orderBy(e => e.resource).toArray();
                    this.mfaList = this.mfaList.filter(e => e.tfaultTime !== 0 && e.tfaultCount !== 0);
                    this.mfaList.forEach(e => {
                        // e.startTime = this.datePipe.transform(e.startTime, 'yyyy-MM-dd');
                        // e.endTime = this.datePipe.transform(e.endTime, 'yyyy-MM-dd');
                        e.tfaultTime = Number.parseFloat((e.tfaultTime / 60).toFixed(2));
                        e.tfaultTimeRate = Number.parseFloat(e.tfaultTimeRate.toFixed(2));
                        e.tfaultCountRate = Number.parseFloat(e.tfaultCountRate.toFixed(2));
                        if(queryModel.querySubAreaIds[0].slice(0,2) === 'GF'){
                            var sub: string = '';
                            sub = e.subArea.replace(/(^\s*)|(\s*$)/g, "");
                            switch(sub){
                                case 'GFAL1': sub += '_装配主线';  break;
                                case 'GFBU1': sub += '_测试线';  break;
                                case 'GFCL1': sub += '_CASE 机加工线';  break;
                                case 'GFCR1': sub += '_行星齿轮组分装线';  break;
                                case 'GFCS1': sub += '_中间支撑架分装线';  break;
                                case 'GFDH1': sub += '_飞轮盘减震器壳体分装线';  break;
                                case 'GFHL1': sub += '_HOUSING 机加工线';  break;
                                case 'GFTC1': sub += '_壳体分装线';  break;
                                case 'GFTD1': sub += '_中间轴&差速器分装线';  break;
                            }
                            e.subArea = sub;
                        }
                    });
                    this.mfaChartsList = this.mfaList;
                    this.getGroupList();
                    this.showCharts(true);
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    /**构建按次数TOP5数据 */
    getGroupList(): void {
        const list = Enumerable.from((this.mfaChartsList));
        const allTotalCount = list.sum(item => item.tfaultCount);
        const allTotalFaultTime = list.sum(item => item.tfaultTime);
        this.mfaGroupList =
            list
                .groupBy(e => e.deviceAlarmNo)
                .select(u => {
                    const temp = new MachineFaultAnalyse();
                    temp.deviceAlarmNo = u.first().deviceAlarmNo;
                    temp.faultWordDescriptionEn = u.first().faultWordDescriptionEn;
                    temp.faultWordDescription = u.first().faultWordDescription;
                    temp.tfaultCount = u.sum(item => item.tfaultCount);
                    temp.tfaultTime = Number.parseFloat(u.sum(item => item.tfaultTime).toFixed(2));
                    temp.tfaultCountRate = Number.parseFloat(((temp.tfaultCount / allTotalCount) * 100).toFixed(2));
                    temp.tfaultTimeRate = Number.parseFloat(((temp.tfaultTime / allTotalFaultTime) * 100).toFixed(2));
                    return temp;
                }).toArray();
        this.countTopItems = Enumerable.from(this.mfaGroupList).orderByDescending(e => e.tfaultCount).take(10).toArray();
        this.timeTopItems = Enumerable.from(this.mfaGroupList).orderByDescending(e => e.tfaultTime).take(10).toArray();
    }

    /**展示报表图表*/
    showCharts(changeTopTime: boolean) {
        const timeArray = Enumerable.from(this.mfaGroupList).orderByDescending(e => e.tfaultTime).toArray();
        const countArray = Enumerable.from(this.mfaGroupList).orderByDescending(e => e.tfaultCount).toArray();

        const x = new Array();
        const y = new Array();
        const x1 = new Array();
        const y1 = new Array();
        const yBar = new Array();

        timeArray.forEach(e => {
            x1.push(e.deviceAlarmNo);
            const bean1 = { value: e.tfaultTime, name: e.deviceAlarmNo };
            y1.push(bean1);


            yBar.push(e.tfaultTime);
        });

        countArray.forEach(e => {
            x.push(e.deviceAlarmNo);
            y.push(e.tfaultCount);
        });

        const yBean = {
            name: '次数',
            type: 'line',
            data: y
        };
        const yBeas = new Array();
        yBeas.push(yBean);
        const legend = ['次数'];
        if (changeTopTime) {
            this.timeChartOption = this.getOption(x1, y1, 'pie');
        }
        this.timeChartOptionBar = this.getOptionBarOfTime(x1, yBar);
        this.countChartOption = ChartOptionCreater.createChartsOption('', '', '次', '', legend, x, yBeas, null);
        this.showloading = false;
    }

    getOption(x: any, y: any, type: String): any {

        // const bean1 = { value: e.tfaultTime, name: '故障代码：\n' + e.deviceAlarmNo + '。\t故障描述：\n' + e.faultWordDescription + '。故障时间' };

        const option = {
            title: {
                text: '',
                subtext: '',
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: (p) => {
                    return '故障代码：' + p.name + ' ，故障时间: ' + p.value + '，  占比：' + p.percent + '%' + '<br/>'
                        + '故障描述：' + this.getDescByCode(p.name);
                },
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: x
            },
            series: [
                {
                    name: '统计信息',
                    type: type,
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: y,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        return option;
    }

    getDescByCode(deviceAlarmNo: any): String {
        return this.mfaList.find(e => e.deviceAlarmNo === deviceAlarmNo).faultWordDescription;
    }

    getOptionBarOfTime(x: any, y: Array<number>) {
        y = y.sort((a, b) => a - b);
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            // legend: {
            //     data: ['2011年']
            // },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
            },
            yAxis: {
                type: 'category',
                data: x
            },
            series: [
                {
                    name: '故障时间：',
                    type: 'bar',
                    data: y
                }
            ]
        };

        return option;
    }

    /**ECharts图表相关*/
    chartsMap = new Map<any, any>();
    onChartInit(index: any, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        if (index === '故障时间分布') {
            echartsIntance.on('legendselectchanged', (obj) => {
                const legend: string = obj.name;
                if (this.mfaChartsList.find(e => e.deviceAlarmNo === legend) !== undefined) {
                    this.mfaChartsList = this.mfaChartsList.filter(e => e.deviceAlarmNo !== legend);
                } else {
                    this.mfaChartsList.push(this.mfaList.find(e => e.deviceAlarmNo === legend));
                }
                this.getGroupList();
                this.showCharts(false);
            });
        }
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }

    @ViewChild("dddb") dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }

    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        const tables = new Array<any>();

        const row1 = new Array();
        this.timeTopItems.forEach((e: MachineFaultAnalyse) => {
            const co = new Array();
            co.push(e.deviceAlarmNo);
            co.push(e.tfaultTime);
            co.push(e.tfaultTimeRate);
            co.push((e.faultWordDescription === null || e.faultWordDescription === undefined) ? '' : e.faultWordDescription);
            co.push('');
            co.push('');
            co.push('');
            row1.push(co);
        });
        const table1 = {
            tableName: '按时间Top10',
            titles: ['故障代码', '故障时间', '故障时间占比(%)', '故障描述', '原因分析', '措施', '状态'],
            rows: row1
        };

        const row2 = new Array();
        this.countTopItems.forEach((e: MachineFaultAnalyse) => {
            const co = new Array();
            co.push(e.deviceAlarmNo);
            co.push(e.tfaultCount);
            co.push(e.tfaultCountRate);
            co.push((e.faultWordDescription === null || e.faultWordDescription === undefined) ? '' : e.faultWordDescription);
            co.push('');
            co.push('');
            co.push('');
            row2.push(co);
        });
        const table2 = {
            tableName: '按次数Top10',
            titles: ['故障代码', '故障次数', '故障次数占比(%)', '故障描述', '原因分析', '措施', '状态'],
            rows: row2
        };

        tables.push(table1);
        tables.push(table2);

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.subArea);
        let resourceStr = '';
        this.equipmentSelected.map(e => e.equipment).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        queryModelArray.push('过滤值:' + this.filterValue + '分钟');
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
        });

        const upload = {
            reportTitle: this.title,
            charts: files,
            queryModel: queryModelArray,
            tables: tables
        };

        this.commServices.exportPdf(upload);
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
